    //
//  CategoriesViewController.m
//  SnowCovered
//
/*
 
 Copyright (c) 2010, Subodh Shakya, Anand Subba Rao, All Rights Reserved
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 
 */
#import "CategoriesViewController.h"
#import "AppDataController.h"
#import "Category.h"
#import "FeaturedViewController.h"
#import "TopAppsViewController.h"
#import "CategoryViewController.h"

@implementation CategoriesViewController
@synthesize catTable;
@synthesize dataController;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataController = [AppDataController sharedController];
    self.navigationItem.title = NSLocalizedString(@"Categories",@"Categories view title " __FILE__ );
}

- (void)viewWillAppear:(BOOL)animated {
    if([[self.dataController appCategories] count] == 0 &&
       [self.dataController loadingCategories] == NO) {
        [self.dataController getCategoriesWithParent:0];
    }
    
    [self.dataController addObserver:self
                          forKeyPath:@"loadingCategories"
                             options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionInitial
                             context:0];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSIndexPath* selectedRow = nil;
    if (selectedRow = [self.catTable indexPathForSelectedRow]) {
        [self.catTable deselectRowAtIndexPath:selectedRow animated:animated];
    }
    
    [self.catTable flashScrollIndicators];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.catTable = nil;
    self.dataController = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark TableView Data Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [[self.dataController appCategories] count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* reuseIdentifier = @"categoryCell";
    
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:reuseIdentifier];
        [cell autorelease];
    }
    
    Category* cat = [[self.dataController appCategories] objectAtIndex:indexPath.row];
    cell.textLabel.text = cat.categoryName;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

#pragma mark -
#pragma mark TableView Data Source
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Category* cat = [[self.dataController appCategories] objectAtIndex:indexPath.row];
        
    [self.dataController setSelectedCategory:cat];
    CategoryViewController* cvc = [[CategoryViewController alloc] init];
    
    [self.navigationController pushViewController:cvc animated:YES];
    [cvc release];
}

#pragma mark -
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if([keyPath isEqual:@"loadingCategories"]) {
        if([self.dataController loadingCategories] == YES)
            [self performSelectorOnMainThread:@selector(transitionToLoading)
                                   withObject:nil
                                waitUntilDone:NO];
        else 
            [self performSelectorOnMainThread:@selector(transitionToTable)
                                   withObject:nil
                                waitUntilDone:NO];
    }
}

- (void)transitionToTable {
    if ([self.catTable superview] == nil) {
        [self.view addSubview:self.catTable];
        [self.catTable reloadData];
    }
}

- (void)transitionToLoading {
    if ([self.catTable superview])
        [self.catTable removeFromSuperview];
}

@end
